// src/utils/axios.js
import axios from 'axios';
import router from '@/router';

const api = axios.create({
baseURL: 'http://localhost:8080/api/auth',
timeout: 10000
});

// 请求拦截器：添加JWT令牌
api.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
} else{
  console.log("token timeout")
}
return config;
},
error => {
return Promise.reject(error);
}
);

// 响应拦截器：处理认证失败
api.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response && error.response.status === 401) {
// 未认证，清除令牌并跳转登录页
localStorage.removeItem('token');
router.push('/login');
}
return Promise.reject(error);
}
);

export default api;
